package com.xiaojiang.controller;

import com.xiaojiang.pojo.Article;
import com.xiaojiang.pojo.PageBean;
import com.xiaojiang.pojo.Result;
import com.xiaojiang.service.ArticleService;
import com.xiaojiang.utils.JwtUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 功能：
 * 作者：小江
 * 日期：2024年08月02日
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @PostMapping
    public Result addArticle(@RequestBody @Validated Article article){
        articleService.addArticle(article);
        return Result.success();
    }


    @GetMapping
    public Result<PageBean<Article>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String state
    ){
       PageBean<Article> pb = articleService.list(pageNum,pageSize,categoryId,state);
       return Result.success(pb);
    }

    @GetMapping("/findId")
    public Result<List<Integer>> findId(){
        List<Integer> ids = articleService.findId();
        return Result.success(ids);
    }

    @GetMapping("/detail")
    public Result<Article> listDetail(Integer id){

        if (id==null){
            return Result.error("id不能为空!");
        }

        List<Integer> ids = articleService.findId();
        // 检查传入的id是否在当前登录用户的文章列表中
        Boolean isId = false;
        for (Integer i : ids){
            if (i.equals(id)){
                isId = true;
                break;
            }
        }
        if (isId){
            Article ld = articleService.listDetail(id);
            return Result.success(ld);
        }else {
            return Result.error("您要查找的ID不存在，请重新输入！");
        }

    }

    @PutMapping
    public Result update(@RequestBody @Validated Article article){
        articleService.update(article);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(Integer id){
        if (id==null){
            return Result.error("不能为空!");
        }
        List<Integer> ids = articleService.findId();
        // 检查传入的id是否在当前登录用户的文章列表中
        Boolean isId = false;
        for (Integer i : ids){
            if (i.equals(id)){
                isId = true;
                break;
            }
        }
        if (isId){
            articleService.delete(id);
            return  Result.success();
        }else {
            return Result.error("您要删除的的ID不存在，请重新输入！");
        }


    }

}
